//
//  UWFriendViewController.m
//  Urban Words
//
//  Created by Tim Brandin on 2011-11-21.
//  Copyright (c) 2011 Sypreme. All rights reserved.
//

#import "UWFriendsController.h"
#import "UWFriendManager.h"
#import "UWFriendDetail.h"
#import "UILabel+UW.h"
#import "UWFriendDetailHistory.h"
#import "UWHistoryController.h"

@implementation UWFriendsController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Friends", @"Friends");
        self.tabBarItem.image = [UIImage imageNamed:@"friends"];
        
        UIView *labelContainer = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 220, 30)];
        labelContainer.backgroundColor = [UIColor clearColor];
        //UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 6, 220, 30)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 210, 30)];
        [label setSpecialText:@"Friends"];
        [labelContainer addSubview:label];
        self.navigationItem.titleView = labelContainer;
        [label release];
        
        UIImage *img = [UIImage imageNamed:@"LogoIcon"];
        
        UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [infoButton setImage:img forState:UIControlStateNormal];
        
        CGRect newFrame = CGRectMake(0.0, 0.0, img.size.width, img.size.height);
        newFrame.origin.x += 15;

        infoButton.frame = newFrame;
        [infoButton addTarget:[[UIApplication sharedApplication] delegate] action:@selector(settings) forControlEvents:UIControlEventTouchUpInside];
        
        [[self navigationItem] setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:infoButton]];
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    friendManager = [UWFriendManager sharedManager];
    
    [friendManager setDelegate:self];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    [friendManager unsetDelegate:self];
    [friendManager release];
    
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [friendManager updateFriends];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //NSLog(@"sections: %i", friendManager.sections);
    return friendManager.sections;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [friendManager getSectionAt:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [friendManager countAtSection:section];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell
    
    UWFriend *friend = [friendManager getFriendAt:indexPath.row atSection:indexPath.section];
    
    [[cell textLabel] setText:friend.name]; 
    //[[cell detailTextLabel] setText:friend.fid];
    // Next the path for the profile image
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@.png", docDir, friend.fid];
    // Check if the image exists
    
    if (!friend.table) {
        friend.table = tableView;
        friend.indexPath = indexPath;
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:pngFilePath]) {
        cell.imageView.image = [UIImage imageWithContentsOfFile:pngFilePath];
    } else {
        cell.imageView.image = [UIImage imageNamed:@"first.png"];
        // Try to save the image
        [friendManager performSelectorInBackground:@selector(downloadImage:) withObject:friend];
    }
    
    //[docDir release];
    //[pngFilePath release];
    [friend release];
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"select friend");
    
    UWFriendDetailHistory *friendViewController = [[UWFriendDetailHistory alloc] initWithNibName:@"UWHistoryController" bundle:nil friend:[friendManager getFullFriendAt:indexPath.row atSection:indexPath.section]];
    [self.navigationController pushViewController:friendViewController animated:YES];
    [friendViewController release];
}

/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];

    tempView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.85];
    
    
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 20)];
    tempLabel.backgroundColor = [UIColor clearColor];
    tempLabel.shadowColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.85];
    tempLabel.shadowOffset = CGSizeMake(0.5, 0.5);
    tempLabel.font = [UIFont fontWithName:@"HelveticaNeueLTPro-BlkCn" size:17];
    tempLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"HeaderFontPattern"]];

    tempLabel.text = [self tableView:tableView titleForHeaderInSection:section];
    [tempView addSubview:tempLabel];
    [tempLabel release];
    return tempView;
}
*/

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [friendManager getAllSections];
}


- (void)friendsChanged:(BOOL)success {
    if (success) {
        [self.tableView reloadData];
    }
}

@end
